<?php

namespace app\admin\controller;


use think\Db;
use think\exception\DbException;
use app\admin\model\Role;
use app\admin\model\Permission;
use think\facade\Url;
use app\admin\model\User as UserModel;
use think\response\Json;

class User extends Base
{
    /**
     * 用户列表
     * @return mixed|\think\Response
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $list = UserModel::order('id','desc')->paginate($this->request->get('limit', 30));
            $data = [
                'code' => 0,
                'msg' => '正在请求中...',
                'count' => $list->total(),
                'data' => $list->items()
            ];
            return Json::create($data);
        }
        return $this->fetch();
    }

    /**
     * 添加用户
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $result = $this->validate($data, 'app\admin\validate\User.add');
            if ($result !== true) {
                $this->error($result);
            }
            try {
                $salt = random(16, 0);
                $password = md5(md5($data['password']) . $salt);
                UserModel::create(array_merge($data, [
                    'password' => $password,
                    'salt' => $salt,
                ]));
            } catch (DbException $exception) {
                $this->error('添加失败', null, $exception->getMessage());
            }
            $this->success('添加成功', Url::build('user/index'));
        }
        return $this->fetch();
    }

    /**
     * 更新用户信息
     * @return mixed
     */
    public function edit()
    {
        //查询当前用户，不存在则抛出异常
        $id = $this->request->param('id');
        $user = UserModel::getOrFail($id);
        if ($this->request->isAjax()) {
            $data = $this->request->post();
            $result = $this->validate($data, 'app\admin\validate\User.edit');
            if ($result !== true) {
                $this->error($result);
            }
            //是否需要修改密码
            if ($data['password']) {
                $user->salt = random(16, 0);
                $user->password = md5(md5($data['password']) . $user->salt);
            }
            $user->username = $data['username'];
            $user->nickname = $data['nickname'];
            try {
                $user->save();
            } catch (DbException $exception) {
                $this->error('更新失败', null, $exception->getMessage());
            }
            $this->success('更新成功', Url::build('index'));
        }
        $this->assign('model', $user);
        return $this->fetch();
    }

    /**
     * 删除用户，软删除
     */
    public function del()
    {
        $ids = $this->request->param('ids');
        if (!is_array($ids)){
            $this->error('参数错误');
        }
        try{
            UserModel::destroy($ids);
        }catch (DbException $exception){
            $this->error('删除失败');
        }
        $this->success('删除成功');
    }

    /**
     * 禁用，启用 用户
     */
    public function status()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        if (!in_array($status,[0,1])){
            $this->error('参数错误');
        }
        $user = UserModel::findOrEmpty($id);
        if ($user->isEmpty()){
            $this->error('数据不存在');
        }
        try{
            $user->status=$status;
            $user->save();
        }catch (DbException $exception){
            $this->error('更新失败',null,$exception->getMessage());
        }
        $this->success('更新成功');
    }

    /**
     * 用户分配角色
     * @return mixed
     * @throws DbException
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function role()
    {
        $id = $this->request->param('id');
        $user = UserModel::with('roles')->where('id',$id)->findOrFail();
        $roles = Role::select();
        foreach ($roles as $k=>$role){
            if (isset($user->roles) && !$user->roles->isEmpty()){
                foreach ($user->roles as $v){
                    if ($role['id']==$v['id']){
                        $roles[$k]['own'] = true;
                    }
                }
            }
        }
        if ($this->request->isAjax()){
            $data = $this->request->param('roles',[]);
            Db::startTrans();
            try{
                //清除原先的角色
                Db::name('user_role')->where('user_id',$id)->delete();
                //添加新的角色
                foreach ($data as $v){
                    Db::name('user_role')->insert([
                        'user_id' => $id,
                        'role_id' => $v,
                    ]);
                }
                Db::commit();
            }catch (DbException $exception){
                Db::rollback();
                $this->error('更新失败',null,$exception->getMessage());
            }
            $this->success('更新成功',Url::build('index'));
        }
        $this->assign('user',$user);
        $this->assign('roles',$roles);
        return $this->fetch();
    }

    public function permission()
    {
        $id = $this->request->param('id');
        $user = UserModel::with('directPermissions')->getOrFail($id);
        $permissions = Permission::order('sort','asc')->select();
        foreach ($permissions as $permission){
            foreach ($user->direct_permissions as $p){
                if ($permission->id==$p['id']){
                    $permission->own = true;
                }
            }
        }
        $permissions = get_tree($permissions->toArray());

        if ($this->request->isAjax()){
            $data = $this->request->param('permissions',[]);
            Db::startTrans();
            try{
                //清除原有的直接权限
                Db::name('user_permission')->where('user_id',$id)->delete();
                //填充新的直接权限
                foreach ($data as $p){
                    Db::name('user_permission')->insert([
                        'user_id' => $id,
                        'permission_id' => $p,
                    ]);
                }
                Db::commit();
            }catch (DbException $exception){
                Db::rollback();
                $this->error('更新失败',null,$exception->getMessage());
            }
            $this->success('更新成功',Url::build('index'));
        }

        $this->assign('permissions',$permissions);
        $this->assign('user',$user);
        return $this->fetch();
    }

}
